<template>
  <div class>
    <form action method="post" class="upload" ref="upload">
      <button class="sign" id="uploadFile">选择文件</button>
      <input type="file" accept=".ipa, .apk" name="upload" id="file" @change="fileSelect($event)" />
    </form>
    <button type="button" class="btn" id="upfile" @click="submit">上传</button>
    <el-upload drag class="avatar-uploader" action="http://name.uiuios.com/api/apkAdmin" accept=".APK" :data="pdfData" :show-file-list="false" :on-progress="beforeAvatarUpload" :on-success="handleSuccess" name="apk">
      <div v-if="videoFlag">
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      </div>
      <el-progress v-else type="circle" :percentage="videoUploadPercent" style="margin-top:30px;"></el-progress>
    </el-upload>
    <el-progress :percentage="50"></el-progress>
    <el-progress :percentage="100" :format="format"></el-progress>
    <el-progress :percentage="100" status="success"></el-progress>
    <el-progress :percentage="100" status="warning"></el-progress>
    <el-progress :percentage="50" status="exception"></el-progress>
  </div>
</template>

<script>
const AppInfoParser = require("app-info-parser");
import { apkAdmin } from '@/api/application'
export default {
  name: "",
  components: {
  },
  data() {
    return {
      percent: 0,
      pdfData: { userId: '', last_ip: '' },
      videoUploadPercent: 0,
      videoFlag: true
    }
  },
  created: function () {
    this.pdfData.userId = this.$store.state.user.token
    this.pdfData.last_ip = sessionStorage.getItem("Ip")
  },
  methods: {
    beforeAvatarUpload(event, file) {
      this.videoFlag = false;
      if (Math.floor(event.percent) <= 99) {
        this.videoUploadPercent = Math.floor(event.percent)
      }
      console.log("是否会触发", event)
      this.apkUnplate = false;//将添加和上传的按钮分开
    },
    handleSuccess(res) {
      this.videoUploadPercent = 100;
      setTimeout(() => {
        this.videoUploadPercent = 0;
        this.videoFlag = true
        console.log("上传成功的会带欧", res)
      }, 500)
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          alert('submit!');
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    //选择文件
    fileSelect(e) {
      this.files = e.target.files[0];

    },
    //解析安装包
    getMsg() {
      const parser = new AppInfoParser(this.files).parse().then(result => {
        let fileName = this.files.name;
        let suffix = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length);
        if (result) {
          this.icon = result.icon;
          if (suffix == 'ipa') {
            if (result.CFBundleDisplayName == undefined) {
              this.appname = result.CFBundleName;
            } else {
              this.appname = result.CFBundleDisplayName;
            }
            this.apppackage = result.CFBundleIdentifier;
            this.appTeamName = result.mobileProvision.TeamName;
            this.appversion = result.CFBundleShortVersionString

            var str = result.mobileProvision.ProvisionsAllDevices;
            var test_v = result.mobileProvision.ProvisionedDevices;
            if (str) {
              this.apptype = "企业版";
            } else {
              if (result.mobileProvision.DeveloperCertificates.length >= 0) {
                this.apptype = '测试版本';
              } else {
                this.apptype = "未签名应用";
              }
            }
            this.isShow = true;
            return;
          }
          if (suffix == 'apk') {
            this.appname = result.application.label[0];
            this.apppackage = result.package;
            this.appversion = result.versionCode;
          }
          this.isShow = true;
        }
      })
    },
    // 上传apk文件
    submit() {
      let that = this
      // 获取表单对象上传apk文件
      var fm = this.$refs.upload;
      // 实例化FormData对象
      var fd = new FormData();
      //添加上传的文件以及token参数
      fd.append('userId', 1)
      fd.append('last_ip', '127.0.0.1')
      fd.append('apk', document.querySelector('input[type=file]').files[0])
      console.log('------请求参数', document.querySelector('input[type=file]').files[0])
      // 创建XMLHttpRequest对象
      var xhr = new XMLHttpRequest();
      // 调用open方法准备ajax请求
      xhr.open('post', 'http://name.uiuios.com/api/apkAdmin');
      var jdt = this.$refs.progressbar;
      // 绑定onprogress事件可获取上传的进度
      xhr.upload.onprogress = function (evt) {
        let percent = (evt.loaded / evt.total).toFixed(2);
        that.percent = parseInt(percent * 100)
        console.log('上传进度', that.percent)
      }
      xhr.onreadystatechange = function () {
        if (xhr.readyState == 4) {
          let data = JSON.parse(xhr.responseText)      //转化为对象便于操作
          console.log(data)
        }
      }
      // 发送ajax请求
      // xhr.send(fd);
      apkAdmin(fd).then(res => {
        console.log("请求成功", res)
      }).catch(err => {
        console.log('请求失败', err)
      })
    },
  },
  mounted: function () { }
}
</script>